<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>景区交易合同管理</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row class="pd20 mt20">
      <a-col :span="6">
        合同名称：
        <a-input placeholder="请输入" v-model="queryForm.contractName" />
      </a-col>
      <a-col :span="6">
        甲方名称：
        <a-input placeholder="请输入" v-model="queryForm.partyName" />
      </a-col>
      <a-col :span="6">
        联系方式：
        <a-input placeholder="请输入" v-model="queryForm.partyContact" />
      </a-col>
      <a-col :span="6">
        身份证/统一信用代码：
        <a-input placeholder="请输入" v-model="queryForm.partyIdCard" />
      </a-col>
      <a-col :span="6">
        合同类型：
        <a-select v-model="queryForm.contractType" placeholder="请选择">
          <a-select-option
            v-for="(item, index) in contractTypeList"
            :key="index"
            :value="item.dictValue"
          >
            {{ item.dictLabel }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        合同状态：
        <a-select v-model="queryForm.contractStatus" placeholder="请选择">
          <a-select-option
            v-for="(item, index) in contractStatusList"
            :key="index"
            :value="item.dictValue"
          >
            {{ item.dictLabel }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="8">
        创建时间范围：
        <a-range-picker
          style="width: 330px; margin-left: 10px"
          v-model="dateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :show-time="{
            hideDisabledOptions: true,
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),
              moment('23:59:59', 'HH:mm:ss'),
            ],
          }"
          format="YYYY-MM-DD HH:mm:ss"
          @change="onChange"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="handleSearch"> 查询 </a-button
        >&emsp;&nbsp;
        <a-button @click="cleanQuery">重置</a-button>
      </a-col>
    </a-row>
    <a-row class="pd20 mt20">
      <a-spin :spinning="loading">
        <a-table
          :scroll="{ x: 500 }"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
        >
          <a slot="name" slot-scope="text">{{ text }}</a>
          <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
          <span slot="action" slot-scope="text, record">
            <a @click="editFn(text, record)" v-hasPermi="['zhonghe:lxzz:edit']"
              >查看</a
            >
            <a-divider type="vertical" />
            <a
              @click="download(text, record)"
              v-hasPermi="['zhonghe:lxzz:edit']"
              >下載</a
            >
            <a-divider type="vertical" />
            <a
              @click="delFn(text, record)"
              v-hasPermi="['zhonghe:lxzz:del']"
              class="red"
              >删除</a
            >
          </span>
        </a-table>
        <div class="page_box">
          <a-pagination
            v-model="queryForm.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total"
            show-size-changer
            :page-size="queryForm.current"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            :show-total="(total) => `共 ${total} 条`"
          ></a-pagination>
        </div>
      </a-spin>
    </a-row>
    <a-modal
      title="两新组织配置"
      :visible="dialogVisible"
      width="60%"
      ok-text="下载"
      cancel-text="取消"
      @cancel="dialogVisible = false"
      @ok="download"
    >
      <contact
        ref="exportContent"
        id="exportContent"
        style="width: 800px"
        :record="record"
      />
    </a-modal>
    <contact
      v-show="false"
      ref="exportContent"
      id="exportContent"
      style="width: 800px"
      :record="record"
    />
  </div>
</template>

<script>
import moment from "moment";
import { Modal } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import contact from "./contact.vue";
export default {
  components: {
    contact,
  },
  data() {
    return {
      loading: true,
      dialogVisible: false,
      record: "",
      queryForm: { current: 20, offset: 1 },
      total: 0,
      form: this.$form.createForm(this, { name: "coordinated" }),
      id: null,
      tableData: [],
      columns: [
        {
          title: "合同ID",
          dataIndex: "contractId",
          key: "contractId",
        },
        {
          title: "合同名称",
          dataIndex: "contractName",
          key: "contractName",
        },
        {
          title: "甲方名称",
          dataIndex: "partyAName",
          key: "partyAName",
        },
        {
          title: "甲方身份证/统一社会信用代码",
          dataIndex: "partyAIdCard",
          key: "partyAIdCard",
        },
        {
          title: "甲方联系方式",
          dataIndex: "partyAContact",
          key: "partyAContact",
        },
        {
          title: "乙方名称",
          dataIndex: "partyBName",
          key: "partyBName",
        },
        {
          title: "乙方身份证/统一社会信用代码",
          dataIndex: "partyBIdCard",
          key: "partyBIdCard",
        },
        {
          title: "乙方联系方式",
          dataIndex: "contractType",
          key: "contractType",
        },
        {
          title: "合同期限",
          dataIndex: "Name",
          key: "Name",
        },
        {
          title: "合同状态",
          dataIndex: "contractStatus",
          key: "contractStatus",
          customRender: (text) => {
            let findOne = this.contractStatusList.find( 
              (item) => item.dictValue == text
            );
            return findOne ? findOne.dictLabel : "";
          },
        },
        {
          title: "签署时间",
          dataIndex: "signDate",
          key: "signDate",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          scopedSlots: { customRender: "action" },
        },
      ],
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      typeList: [
        {
          value: "1",
          label: "非公有经济组织",
        },
        {
          value: "2",
          label: "公有经济组织",
        },
      ],
      statusList: [
        {
          value: 0,
          label: "正常",
        },
        {
          value: 1,
          label: "异常",
        },
        {
          value: 2,
          label: "停业",
        },
      ],
      contractStatusList: [],
      contractTypeList: [],
      dateRange: "",
    };
  },
  async mounted() {
    await this.getDictList();
    await this.getList();
  },
  methods: {
    moment,
    handleSearch() {
      this.queryForm.offset = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      const url =
        "/government-platform-center/xunjian/transactionContract/queryByPage";
      const data = this.queryForm;
      this.$axios.post(url, data).then((res) => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.map((item) => {
            this.statusList.forEach((i) => {
              if (i.value == item.status) {
                item["statusName"] = i.label;
              }
            });
            this.typeList.forEach((i) => {
              if (i.value == item.twoNewOrganizationType) {
                item["typeName"] = i.label;
              }
            });
            return item;
          });
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },
    getDictList() {
      this.$axios
        .get(
          "/government-platform-center/dictData/queryByCode?dictType=CONTRACT_STATUS_CODE"
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.contractStatusList = res.data.data;
          }
        });
      this.$axios
        .get(
          "/government-platform-center/dictData/queryByCode?dictType=CONTRACT_TYPE_CODE"
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.contractTypeList = res.data.data;
          }
        });
    },
    cleanQuery() {
      this.queryForm = { current: 20, offset: 1 };
      this.dateRange = "";
      this.getList();
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.current = pageSize;
      this.queryForm.offset = 1;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    delFn(text, record) {
      const that = this;
      Modal.confirm({
        title: "确认删除",
        content: "您确定要删除这项内容吗？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const url = `/government-platform-center/twoNewOrganization?id=${text.id}`;
          that.$axios.delete(url).then((res) => {
            if (res.data.code == 0) {
              that.getList();
              message.success("操作成功");
            }
          });
        },
        onCancel() {
          // 在此处理取消逻辑
          console.log("删除已取消");
        },
      });
    },
    goData(text, record) {
      this.$router.push({
        path: "/dataDict",
        query: { dictType: text.dictType, id: text.id },
      });
    },
    addFn() {
      this.dialogVisible = true;
      this.id = null;
      this.form.resetFields();
    },
    editFn(text, record) {
      this.record = text;
      this.dialogVisible = true;
    },
    download(text, record) {
      this.record = record;
      // 获取要导出的HTML内容
      const content = document.getElementById("exportContent").innerHTML;

      // 构建完整的HTML结构（Word兼容）
      const fullHtml = `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            <style>
              table { border-collapse: collapse; }
              td, th { padding: 5px; }
            </style>
          </head>
          <body>
            ${content}
          </body>
        </html>
      `;

      // 创建Blob对象
      const blob = new Blob([fullHtml], { type: "application/msword" });

      // 创建下载链接
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = `document_${new Date().toISOString().slice(0, 10)}.doc`;

      // 触发下载
      link.click();
      URL.revokeObjectURL(link.href);
    },
    putDict() {
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        }
        if (!this.id) {
          const form = values;
          form.registerTime = dayjs(form.registerTime).format("YYYY-MM-DD");
          form.pushTime = dayjs(form.pushTime).format("YYYY-MM-DD");
          const url = "/government-platform-center/twoNewOrganization";
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.reSetForm();
                this.dialogVisible = false;
                message.success("操作成功");
              }
            });
        } else {
          const form = { ...values, id: this.id };
          form.registerTime = dayjs(form.registerTime).format("YYYY-MM-DD");
          form.pushTime = dayjs(form.pushTime).format("YYYY-MM-DD");
          const url = "/government-platform-center/twoNewOrganization/edit";
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.reSetForm();
                this.dialogVisible = false;
                message.success("操作成功");
              }
            });
        }
      });
    },
    reSetForm() {
      // this.form = { dictName: null, dictType: null, remark: null }
    },
    onChange(val) {
      this.queryForm.startTime = val[0];
      this.queryForm.endTime = val[1];
    },
  },
};
</script>

<style lang="scss" scoped>
.ant-row {
  border-radius: 5px;

  background: #fff;
  color: #000;
}

v-deep {
  .ant-table-thead > tr > th {
    color: #000;
    font-weight: bold;
  }
  .ant-table-tbody > tr > td {
    color: #000;
  }
  .el-table thead {
    color: black;
    font-weight: bold;
    background: #fafafa;
  }
  .el-table th.el-table__cell {
    background: #fafafa;
  }
}
::v-deep .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold !important;
}
.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

@media screen and (max-width: 1300px) {
  .el-input {
    width: 70%;
  }

  .el-select {
    width: 70%;
  }

  .app {
    width: calc(100% - 50px);
  }
}

@media screen and (max-width: 1100px) {
  .el-input {
    width: 90%;
  }

  .el-select {
    width: 90%;
  }
}
</style>
